<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="新闻标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入新闻标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button v-hasPermi="['land:news:query']" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['land:news:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['land:news:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="新闻标题" align="center" prop="title" />
      <el-table-column label="是否展示" align="center" prop="isshow">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_news_isshow" :value="scope.row.isshow" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['land:news:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['land:news:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="新闻标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入新闻标题" />
        </el-form-item>
        <el-form-item label="新闻内容" prop="contents">
          <editor v-model="form.contents" :min-height="192" />
        </el-form-item>
        <el-form-item label="新闻信息图片" prop="fileList">
          <el-upload ref="picUpload" :action="baseUrl" list-type="picture-card" :headers="headerConfig" :file-list="fileList" :on-success="handleSuccess">
            <i slot="default" class="el-icon-plus" />
            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in" />
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete" />
                </span>
              </span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否展示" prop="isshow">
          <el-radio-group v-model="form.isshow">
            <el-radio
              v-for="dict in dict.type.sys_news_isshow"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { listPost, addPost, getPost, updatePost, delPost } from '@/api/land/news'
import { getToken } from '@/utils/auth'

export default {
  name: 'News',
  dicts: ['sys_news_isshow'],
  data() {
    return {
      baseEnv: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: '新闻新增',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        newsType: 4
      },
      // 表单参数
      form: {
        isshow: undefined
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: '请输入新闻标题', trigger: 'blur' }
        ],
        contents: [
          { required: true, message: '请输入新闻内容', trigger: 'blur' }
        ],
        isshow: [
          { required: true, message: '请选择', trigger: 'blur' }
        ]
      },
      baseUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      headerConfig: { Authorization: 'Bearer ' + getToken() },
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      newArr: [],
      itemId: undefined
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      listPost(this.queryParams).then(response => {
        this.postList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
      }
      this.resetForm('form')
      this.newArr = []
      this.fileList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加新闻'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const postId = row.id || this.ids
      this.itemId = row.id
      getPost(postId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改新闻'
        this.form.isshow = response.data.isshow.toString()
        const arrNew = []
        if (response.data.landNews && response.data.landNews.length > 0) {
          response.data.landNews.forEach((item) => {
            const obj = {}
            const objNew = {}
            obj.name = item.fileName
            obj.url = this.baseEnv + item.filePath
            objNew.fileName = item.fileName
            objNew.filePath = item.filePath
            this.fileList.push(obj)
            arrNew.push(objNew)
          })
        }
        this.newArr = arrNew
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.itemId !== undefined) {
            this.form.landNews = this.newArr
            updatePost(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            this.form.landNews = this.newArr
            this.form.newsType = 4
            addPost(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.id || this.ids
      this.$modal.confirm('是否确认删除选中项？').then(function() {
        return delPost(postIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    handleRemove(file) {
      if (file.response) {
        this.newArr = this.newArr.filter((item) => { return file.response.fileName !== item.filePath })
        const uploadFiles = this.$refs.picUpload.uploadFiles
        for (let i = 0; i < uploadFiles.length; i++) {
          if (uploadFiles[i].response) {
            if (uploadFiles[i].response.fileName === file.response.fileName) {
              uploadFiles.splice(i, 1)
            }
          } else {
            if (uploadFiles[i].url.split(this.baseEnv)[1] === file.response.fileName) {
              uploadFiles.splice(i, 1)
            }
          }
        }
      } else {
        if (file.url) {
          this.newArr = this.newArr.filter((item) => { return file.url.split(this.baseEnv)[1] !== item.filePath })
          const uploadFiles = this.$refs.picUpload.uploadFiles
          for (let i = 0; i < uploadFiles.length; i++) {
            if (uploadFiles[i].url === file.url) {
              uploadFiles.splice(i, 1)
            }
          }
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSuccess(response, file, fileList) {
      const obj = {}
      obj.fileName = file.response.originalFilename
      obj.filePath = file.response.fileName
      this.newArr.push(obj)
    },
    goodsBannerchan(e) {
      this.form.landNews = e
    }
  }
}
</script>
<style scoped lang="scss">
// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
    transition: all 0s;
}

::v-deep .el-list-enter, .el-list-leave-active {
    opacity: 0;
    transform: translateY(0);
}
</style>
